import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import request from 'utils/request';
import { RootState } from '../store';
import { getEndian } from 'utils/path';

const namespace = 'user';
const TOKEN_NAME = 'ai_transport_token';

const initialState = {
  token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
  userInfo: {},
};

// login
export const login = createAsyncThunk(`${namespace}/login`, async (userInfo: Record<string, unknown>) => {
  console.log('login user info:', userInfo);
  // const mockLogin = async (userInfo: Record<string, unknown>) => {
  // 登录请求流程
  // console.log(userInfo);
  // const { account, password } = userInfo;
  // if (account !== 'td') {
  //   return {
  //     code: 401,
  //     message: '账号不存在',
  //   };
  // }
  // if (['main_', 'dev_'].indexOf(password) === -1) {
  //   return {
  //     code: 401,
  //     message: '密码错误',
  //   };
  // }
  // const token = {
  //   main_: 'main_token',
  //   dev_: 'dev_token',
  // }[password];
  //   return {
  //     code: 200,
  //     message: '登陆成功',
  //     data: 'main_token',
  //   };
  // };

  // const res = await mockLogin(userInfo);
  // if (res.code === 200) {
  //   return res.data;
  // }
  // throw res;
  const res = await request.post('/api/v1/user/login', { phone: userInfo.phone, password: userInfo.password });
  console.log('res:', res);
  // if (res?.code === 'OK') {
  //   // localStorage.setItem(TOKEN_NAME, res.data);
  //   request
  //     .get('/api/v1/user/me')
  //     .then((res) => {
  //       console.log('me: ', res);
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //     })
  //     .finally(() => {});
  // }
  // return res;
  // if (res?.code === 'OK') {
  //   return res;
  // }
  // throw res;
});

// getUserInfo
export const getUserInfo = createAsyncThunk(`${namespace}/getUserInfo`, async (_, { getState }: any) => {
  const { token } = getState();
  // const mockRemoteUserInfo = async (token: string) => {
  //   if (token === 'main_token') {
  //     return {
  //       name: 'td_main',
  //       roles: ['all'],
  //     };
  //   }
  //   return {
  //     name: 'td_dev',
  //     roles: ['userIndex', 'dashboardBase', 'login'],
  //   };
  // };
  //
  // const res = await mockRemoteUserInfo(token);
  // const res = await request.get('/api/v1/user/me');
  // if (res?.code === 'OK') {
  //   // localStorage.setItem(TOKEN_NAME, res.data);
  //   request
  //     .get('/api/v1/user/me')
  //     .then((res) => {
  //       console.log('me: ', res);
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //     })
  //     .finally(() => {});
  // }
  // console.log('getUserInfo', res);
  // if (!res?.data?.id) {
  //   location.href = `/${getEndian()}/login`;
  // }
  // return res;
});

const userSlice = createSlice({
  name: namespace,
  initialState,
  reducers: {
    logout: (state) => {
      localStorage.removeItem(TOKEN_NAME);
      state.token = '';
      state.userInfo = {};
    },
    remove: (state) => {
      state.token = '';
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(login.fulfilled, (state, action) => {
        console.log('action.playload:', action.payload);
        // localStorage.setItem(TOKEN_NAME, action.payload.data);
        // state.token = action.payload.data;
      })
      .addCase(getUserInfo.fulfilled, (state, action) => {
        // console.log('getUserInfo', action.payload.data);
        // state.userInfo = action.payload.data;
      });
  },
});

export const selectUser = (state: RootState) => state.user;

export const { logout, remove } = userSlice.actions;

export default userSlice.reducer;
